#!/usr/bin/env python
#coding:utf-8
from simple_spider import url_manager, html_downloader, html_parser, html_outputer


class SpiderMain(object):
    def __init__(self):
        # 初始化各个模块
        self.urls = url_manager.UrlManager()
        self.downloader = html_downloader.HtmlDownloader()
        self.parser = html_parser.HtmlParser()
        self.outputer = html_outputer.HtmlOutputer()
    
    def craw(self, root_url):
        count = 1
        # 将入口url添加到urls
        self.urls.add_new_url(root_url)
        # 执行爬虫调度器，通过while循环执行爬取功能
        while self.urls.has_new_url():
            try:
                # 获取一个新的url
                new_url = self.urls.get_new_url()
                # 打印爬取url的编号
                print 'craw No.%d : %s' % (count, new_url)
                # 使用downloader下载器获取url的页面内容
                html_cont = self.downloader.download(new_url)
                # 获取从url中解析出来的新url和数据
                new_urls, new_data = self.parser.parse(new_url,html_cont)
                # 添加新获取的new_urls
                self.urls.add_new_urls(new_urls)
                # 使用outputer收集数据
                self.outputer.collect_data(new_data)
                # 爬取10个后就退出
                if count == 10:
                    break
                count = count + 1
            except:
                print 'craw failed...'
        # 输出爬取的数据
        self.outputer.output_html()

# 声明主函数
if __name__=="__main__":
    # 入口URL
    root_url = "http://baike.baidu.com/view/1139590.htm"
    # 调用SpiderMain主程序
    obj_spider = SpiderMain()
    # 执行craw爬取方法
    obj_spider.craw(root_url)